/**
 * 由于WebSocket真机连接问题，此处采用长轮询方式实现消息同步
 */
function PollingSocket (option) {
  this.option = {
    url: option['url'],  // 连接地址
    onSocketMessage: option['onSocketMessage'] || null,  // 监听Socket接受到服务器的消息事件
    onSocketError: option['onSocketError'] || null,  // 监听Socket请求失败的消息事件
    onSocketClose: option['onSocketClose'] || null,  // 监听Socket请求关闭的消息事件
    duration: option['duration'] || 30,  // 连接持续时间，默认30秒
    interval: option['interval'] || 3 // 请求间隔时间，默认3秒
  }
  this.request = null
  this.intervalTask = null
  this.timeoutTask = null
}
PollingSocket.prototype.start = function () {
  let vm = this
  // 定时关闭连接
  this.timeoutTask = setTimeout(function () {
    vm.stop()
  }, this.option.duration * 1000)
  // 周期请求
  socketRequest(vm, vm.option)
  this.intervalTask = setInterval(function () {
    if (vm.request) {
      vm.request.abort()
    }
    socketRequest(vm, vm.option)
  }, this.option.interval * 1000)
  
}
PollingSocket.prototype.stop = function () {
  if (this.intervalTask) {
    clearInterval(this.intervalTask)
    if (this.request) {
      this.request.abort()
    }
    if (this.option.onSocketClose && (typeof this.option.onSocketClose === 'function')) {
      this.option.onSocketClose.call(this)
    }
  }
}
/**
 * 发起请求
 */
function socketRequest(vm, option) {
  vm.request = wx.request({
    url: option.url,
    data: {
      'Rememberme': wx.getStorageSync('token')
    },
    header: {
      'content-type': 'application/json'
    },
    success: (res) => {
      if (option.onSocketMessage && (typeof option.onSocketMessage === 'function')) {
        option.onSocketMessage.call(vm, res)
      }
    },
    fail: () => {
      if (option.onSocketError && (typeof option.onSocketError === 'function')) {
        option.onSocketError.call(vm)
      }
    },
    complete: () => {
      vm.request = null
    }
  })
}
module.exports = PollingSocket